﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FFmpegWinui3.MediaFolder
{
    public class Clock
    {
        private readonly Stopwatch Chrono = new Stopwatch();

        private readonly Object SyncLock = new object();
        public Clock()
        {
            Reset();
        }

        public void Play()
        {
            lock (SyncLock)
            {
                if (Chrono.IsRunning) return;
                Chrono.Start();
            }
        }
        public bool IsRuning { get { lock (SyncLock) { return Chrono.IsRunning; } } }
        private double _speedRadio=1d;
        public double SpeedRatio
        {
            get { lock (SyncLock) { return _speedRadio; } }
            set { lock (SyncLock) { if (value < 0d) value = 0d; _speedRadio = value; } }
        }

        private double OffsetMilliseconds = 0;

        public TimeSpan Position
        {
            get
            {
                lock (SyncLock)
                    return TimeSpan.FromTicks((long)Math.Round(
                       (OffsetMilliseconds + (Chrono.ElapsedMilliseconds * SpeedRatio)) * TimeSpan.TicksPerMillisecond, 0));
            }
            set
            {
                var resume = Chrono.IsRunning;
                Chrono.Reset();
                OffsetMilliseconds = value.TotalMilliseconds;
                if (resume) Chrono.Start();
            }
        }



        public void Pause()
        {
            Chrono.Stop();
        }

        public void Reset()
        {
            lock (SyncLock)
            {
                Chrono.Reset();
            }
        }

    }
}
